<script setup>
import { computed } from "vue";
import MonthPicker from "./MonthPicker.vue";
import YearPicker from "./YearPicker.vue";

const props = defineProps(["year", "month", "state"]);
const emit = defineEmits(["change", "monthClick", "yearClick"]);
const today = new Date();
const month = computed(() => props.month === undefined ? today.getMonth() : props.month);
const year = computed(() => props.year === undefined ? today.getFullYear() : props.year);
const showControl = computed(() => props.state == "calendar");

function changeMonth(offset) {
  const result = { year: year.value, month: month.value + offset };
  while (result.month < 0) {
    result.month += 12;
    result.year -= 1;
  }
  while (result.month >= 12) {
    result.month -= 12;
    result.year += 1;
  }
  emit("change", result);
}

function changeYear(offset) {
  const result = { year: year.value + offset, month: month.value };
  emit("change", result);
}
</script>

<template>
  <div class="date-picker-header">
    <MonthPicker class="month-picker" :month="month" :showControl="showControl" @change="changeMonth"
      @click="$emit('monthClick')"></MonthPicker>
    <YearPicker class="year-picker" :year="year" :showControl="showControl" @change="changeYear"
      @click="$emit('yearClick')">
    </YearPicker>
  </div>
</template>

<style scoped>
.date-picker-header {
  display: flex;
}

.year-picker {
  margin-left: auto;
}
</style>